<template>
  <el-dialog
    width="60%"
    :visible.sync="dialogVisibleShow"
    :close-on-click-modal="false"
    :title="dialogType === 'edit' ? '编辑医护人员' : '新增医护人员'"
    :before-close="handleClose"
  >
    <el-tabs type="border-card" v-model="activeName">
      <el-tab-pane label="基本信息" name="basicInfo">
        <el-container>
          <el-aside width="70%">
            <el-form
              :model="staff"
              :rules="rules"
              ref="staffForm"
              label-width="110px"
              label-position="right"
            >
              <el-form-item label="员工工号：" prop="staffCode">
                <el-input v-model="staff.staffCode"></el-input>
              </el-form-item>
              <el-form-item label="员工姓名：" prop="name">
                <el-input v-model="staff.name"></el-input>
              </el-form-item>

              <el-form-item label="身份证号：" prop="idCard">
                <el-input v-model="staff.idCard"></el-input>
              </el-form-item>
              <el-form-item label="性别：">
                <el-radio v-model="staff.sex" :label="1" disabled>男</el-radio>
                <el-radio v-model="staff.sex" :label="2" disabled>女</el-radio>
              </el-form-item>

              <el-form-item label="出生日期：">
                <el-date-picker
                  v-model="staff.birthday"
                  type="date"
                  placeholder="请选择出生日期"
                  align="right"
                  value-format="yyyy-MM-dd"
                  format="yyyy-MM-dd"
                  readonly
                >
                </el-date-picker>
              </el-form-item>
              <el-form-item label="其他证件类型：">
                <el-select
                  v-model="staff.otherCredType"
                  clearable
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in certificateOptions"
                    :key="item.basicId"
                    :label="item.entryValue"
                    :value="item.basicId"
                  >
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="其他证件号码：">
                <el-input v-model="staff.otherCredEntial"></el-input>
              </el-form-item>
              <el-form-item label="民族：">
                <el-select
                  v-model="staff.nation"
                  clearable
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in nationOptions"
                    :key="item.basicId"
                    :label="item.entryValue"
                    :value="item.basicId"
                  >
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="婚姻状况：">
                <el-select
                  v-model="staff.maritalStatus"
                  clearable
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in maritalOptions"
                    :key="item.basicId"
                    :label="item.entryValue"
                    :value="item.basicId"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="学历：">
                <el-select
                  v-model="staff.education"
                  clearable
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in educationOptions"
                    :key="item.basicId"
                    :label="item.entryValue"
                    :value="item.basicId"
                  >
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="资质编码：" prop="qualifId">
                <el-input v-model="staff.qualifId"></el-input>
              </el-form-item>
              <el-form-item label="所属科室：" prop="hisDeptId">
                <template>
                  <treeselect
                    v-model="staff.hisDeptId"
                    :options="deptTreeData"
                    :load-options="loadDeptOptions"
                    noChildrenText="请选择科室"
                    @select="chooseDept"
                    :normalizer="normalizer"
                    placeholder="请选择科室"
                  >
                  </treeselect>
                </template>
              </el-form-item>

              <el-form-item label="职称：" prop="titleCode">
                <el-select
                  v-model="staff.titleCode"
                  clearable
                  filterable
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in titleCodeOptions"
                    :key="item.hisDicId"
                    :label="item.standardName"
                    :value="item.hisDicId"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="业务类别：" prop="businessType">
                <el-select
                  v-model="staff.businessType"
                  clearable
                  filterable
                  placeholder="请选择"
                >
                  <el-option label="门诊" value="1"></el-option>
                  <el-option label="住院" value="2"></el-option>
                  <el-option label="门诊和住院" value="3"></el-option>
                  <el-option label="公卫" value="4"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="管理类别：" prop="administerType">
                <el-select
                  v-model="staff.administerType"
                  clearable
                  filterable
                  placeholder="请选择"
                >
                  <el-option label="全部" value="1"></el-option>
                  <el-option label="公卫" value="2"></el-option>
                  <el-option label="医疗" value="3"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="手机号码：" prop="telephone">
                <el-input v-model="staff.telephone"></el-input>
              </el-form-item>

              <el-form-item label="地址：">
                <el-input v-model="staff.address"></el-input>
              </el-form-item>
            </el-form>
          </el-aside>
          <el-main>
            <div>
              <!-- <el-upload
                class="avatar-uploader"
                :headers="headers"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                :action="photoUploadAddr"
                :show-file-list="false"
              >
                <img v-if="photoImageUrl" :src="photoImageUrl" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                <el-button type="primary">上传相片</el-button>
              </el-upload> -->

              <!-- <el-upload
                class="avatar-uploader"
                :headers="headers"
                :before-upload="beforeAvatarUpload"
                :on-success="handleSignatureSuccess"
                :action="esignatureUploadAddr"
                :show-file-list="false"
              >
                <img v-if="esignImageUrl" :src="esignImageUrl" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                <el-button type="primary">上传电子签名</el-button>
              </el-upload> -->
            </div>
          </el-main>
        </el-container>
      </el-tab-pane>

      <el-tab-pane label="个人简历" name="resume">
        <el-row>
          <el-col :span="24">
            <el-container>
              <el-aside width="20%" align="right" style="margin-top: 30px;"
                ><span>个人简历：</span></el-aside
              >
              <el-main
                ><el-input
                  v-model="staff.profiles"
                  :rows="10"
                  type="textarea"
                  maxlength="300"
                  show-word-limit
                ></el-input
              ></el-main>
            </el-container>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-container>
              <el-aside width="20%" align="right" style="margin-top: 30px;"
                ><span>擅长领域：</span></el-aside
              >
              <el-main
                ><el-input
                  v-model="staff.expertise"
                  type="textarea"
                  :rows="10"
                  maxlength="300"
                  show-word-limit
                ></el-input
              ></el-main>
            </el-container>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-container>
              <el-aside width="20%" align="right" style="margin-top: 30px;"
                ><span>成果荣誉：</span></el-aside
              >
              <el-main
                ><el-input
                  v-model="staff.honour"
                  type="textarea"
                  :rows="10"
                  maxlength="300"
                  show-word-limit
                ></el-input
              ></el-main>
            </el-container>
          </el-col>
        </el-row>
      </el-tab-pane>
      <el-tab-pane label="系统账号" name="systemAccount">
        <el-container>
          <el-main>
            <el-form :model="staff" :rules="rules" ref="systemAccountForm">
              <el-form-item label="登录账号" prop="userName">
                <el-input
                  v-model="staff.userName"
                  auto-complete="new-password"
                ></el-input>
              </el-form-item>
              <el-form-item label="登录密码" prop="password">
                <el-input
                  v-model="staff.password"
                  type="password"
                  auto-complete="new-password"
                ></el-input>
              </el-form-item>
              <el-form-item label="确认密码" prop="confirmPassword">
                <el-input
                  v-model="staff.confirmPassword"
                  type="password"
                ></el-input>
              </el-form-item>
              <el-form-item label="角色" prop="roleIdArr">
                <el-select
                  v-model="staff.roleIdArr"
                  multiple
                  value=""
                  placeholder=""
                  style="width:100%"
                >
                  <el-option
                    v-for="item in roles"
                    :key="item.ROLEID"
                    :label="item.ROLENAME"
                    :value="String(item.ROLEID)"
                  />
                </el-select>
              </el-form-item>
            </el-form>
          </el-main>
        </el-container>
      </el-tab-pane>
    </el-tabs>
    <span slot="footer" class="dialog-footer">
      <el-button @click="resetTabInfo">重 置</el-button>
      <el-button type="primary" :disabled="saveDisabled" @click="confirmStaff"
        >确 定</el-button
      >
    </span>
  </el-dialog>
</template>

<script>
import {
  checkUserNameExist,
  getStaffByStaffCode,
  updateMedicalStaff,
  addMedicalStaff,
  getCurrentSysOrg,
  getDeptsBySysOrgId,
  getOrgAndDeptLazyLoad,
  getChildDeptByHisDeptId,
  checkExistStaffByTelephone,
  getDrugType,
  getDoctorTitle,
  getAllRoleIdAndName
} from "@/api/setup/doctors-setup.js"
import {
  mzdmCode,
  hyzkdmCode,
  xldmCode,
  zjlxCode,
  zyjszwdmCode,
  departmentType,
  deptCategory
} from "@/api/setup/medicalstaff.js"
import {
  LOAD_CHILDREN_OPTIONS,
  LOAD_ROOT_OPTIONS
} from "@riophae/vue-treeselect"
import qs from "qs"
import { cardid } from "@/utils/validate"
const defaultPassword = ""
const defaultStaff = {
  staffCode: "",
  name: "",
  idCard: "",
  sex: "",
  birthday: "",
  otherCredType: "",
  otherCredEntial: "",
  nation: "",
  maritalStatus: "",
  education: "",
  qualifId: "",
  hisDeptId: null,
  titleCode: "",
  businessType: "",
  telephone: "",
  address: "",
  sysOrganizationId: "",
  profiles: "",
  expertise: "",
  administerType: null,
  honour: "",
  photoUrl: "",
  eSignature: "",
  userName: "",
  password: defaultPassword,
  confirmPassword: defaultPassword,
  roleId: "",
  roleIdArr: [],
  sysUserId: null
}
export default {
  props: {
    dialogVisibleShow: {
      type: Boolean,
      default: false
    },
    selectedDept: {
      type: Object
    },
    organizationId: {
      type: String
    }
  },
  components: {},
  data() {
    // 校验员工工号不能重复
    const validateStaffCode = (rule, value, callback) => {
      if (value && value.trim()) {
        let pattern = /^[a-zA-Z0-9]+$/
        if (!pattern.test(value)) {
          callback(new Error("员工工号只能为数字、字母"))
        } else {
          if (value.length > 20) {
            callback(new Error("员工工号最大长度为20"))
          } else {
            if (
              this.dialogType == "new" ||
              (this.dialogType == "edit" && this.oldStaffCodeVal != value)
            ) {
              // getStaffByStaffCode(value).then(response => {
              //   console.log(response)
              //   if (!response.data.data) {
              //     callback("员工工号已存在")
              //   } else {
              //     callback()
              //   }
              // })
              callback()
            } else {
              callback()
            }
          }
        }
      }
    }
    const validateStaffName = (rule, value, callback) => {
      if (value && value.trim()) {
        let pattern = /^[\u4e00-\u9fa5a-zA-Z]+$/
        if (!pattern.test(value)) {
          callback(new Error("员工姓名只能为中文、字母"))
        } else {
          let len = 0
          for (let i = 0; i < value.length; i++) {
            let c = value.charCodeAt(i)
            //单字节加1
            if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) {
              len++
            } else {
              len += 2
            }
          }
          if (len > 100) {
            callback(new Error("员工姓名最多为100字符"))
          } else {
            callback()
          }
        }
      }
    }
    // 校验身份证号格式，格式正确则根据身份证号填充性别和出生日期
    const validateIdCard = (rule, value, callback) => {
      if (value && value.trim()) {
        let list = cardid(value)
        if (list[0]) {
          this.staff.birthday = ""
          this.staff.sex = ""
          callback(new Error(list[1]))
        } else {
          let birthY, birthM, birthD
          if (15 == value.length) {
            // 15位身份证号
            birthY = value.substring(6, 8)
            birthM = value.substring(8, 10)
            birthD = value.substring(10, 12)
            this.staff.birthday = "19" + birthY + "-" + birthM + "-" + birthD
            // 15位身份证号最后一位：男为奇数，女为偶数
            value.substring(14) % 2 == 0
              ? (this.staff.sex = 2)
              : (this.staff.sex = 1)
          } else {
            // 18位身份证号
            birthY = value.substring(6, 10)
            birthM = value.substring(10, 12)
            birthD = value.substring(12, 14)
            this.staff.birthday = birthY + "-" + birthM + "-" + birthD
            // 18位身份证号的第17位：男为奇数，女为偶数
            value.substring(16, 17) % 2 == 0
              ? (this.staff.sex = 2)
              : (this.staff.sex = 1)
          }
          callback()
        }
      }
    }
    // 选择科室
    const validateStaffDept = (rule, value, callback) => {
      if (value && value.trim()) {
        if (
          this.dialogType == "new" ||
          (this.dialogType == "edit" && this.oldStaffDept != value)
        ) {
          let idx = deptCategory.administrationDept.findIndex(
            (value, index, arr) => {
              return this.choosedNodeDeptCategory == value
            }
          )
          if (
            this.choosedNodeType != "dept" ||
            !this.choosedNodeIsLeaf ||
            this.choosedNodeDeptCategory == -1
          ) {
            callback(new Error("请选择科室"))
          } else {
            callback()
          }
        } else {
          callback()
        }
      }
    }
    //检查手机号是否已存在
    const validaTelephone = (rule, value, callback) => {
      if (value && value.trim()) {
        if (
          this.dialogType == "new" ||
          (this.dialogType == "edit" && this.oldStaffCodeVal != value)
        ) {
          let hisMedicalStaffId =
            this.staff == null ? null : this.staff.hisMedicalStaffId
          let para = { telephone: value, hisMedicalStaffId: hisMedicalStaffId }
          // checkExistStaffByTelephone(para).then(response => {
          //   if (response.data.code == "1000") {
          //     if (response.data.data) {
          //       callback("手机号已存在")
          //     } else {
          //       callback()
          //     }
          //   }
          // })
          callback()
        } else {
          callback()
        }
      }
    }
    // 修改系统账号时，登录账号不能为空
    const validateSysUserName = (rule, value, callback) => {
      // sysUserId不为null，则是修改系统账户，登录账号不能为空
      if (this.staff.sysUserId) {
        if (value === "") {
          callback(new Error("修改系统账号时，登录账号不能为空"))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    // 校验登录用户是否存在
    const validateUserNameExist = (rule, value, callback) => {
      if (value && value.trim()) {
        if (
          this.dialogType == "new" ||
          (this.dialogType == "edit" && this.oldUserName != value)
        ) {
          // checkUserNameExist(value).then(response => {
          //   let id = this.staff.hisMedicalStaffId
          //   if (response.data.data != null) {
          //     if (response.data.data.hisMedicalStaffId == null) {
          //       callback()
          //     } else {
          //       if (
          //         response.data.data.hisMedicalStaffId !=
          //         this.staff.hisMedicalStaffId
          //       ) {
          //         callback("登录帐号已被绑定到" + response.data.data.name)
          //       }
          //     }
          //   } else {
          //     callback()
          //   }
          // })
          callback()
        } else {
          callback()
        }
      }
    }
    //  验证密码
    const validatePassword = (rule, value, callback) => {
      let pattern = /^[a-zA-Z0-9!@#$%^&*]{6,20}$/
      if (this.staff.userName !== "") {
        if (this.staff.sysUserId === null) {
          if (!value) {
            callback(new Error("新增系统账号，登录账号不为空时，密码不能为空"))
          } else {
            if (pattern.test(value)) {
              if (this.staff.password) {
                this.$refs.systemAccountForm.validateField("confirmPassword")
              }
              callback()
            } else {
              callback(
                new Error(
                  "密码只能为数字、字母或!、@、#、$、%、^、&、*等字符，长度6到20位"
                )
              )
            }
          }
        } else {
          // 修改系统账号，若密码不为空，则校验密码
          if (value) {
            if (pattern.test(value)) {
              this.$refs.systemAccountForm.validateField("confirmPassword")
              callback()
            } else {
              this.$refs.systemAccountForm.validateField("confirmPassword")
              callback(
                new Error(
                  "密码只能为数字、字母或!、@、#、$、%、^、&、*等字符，长度6到20位"
                )
              )
            }
          } else {
            this.$refs.systemAccountForm.validateField("confirmPassword")
            callback()
          }
        }
      } else {
        callback()
      }
    }
    // 验证密码是否一致
    const validateConfirmPassword = (rule, value, callback) => {
      if (this.staff.userName !== "") {
        if (this.staff.sysUserId === null) {
          if (!value) {
            callback(new Error("请再次输入密码"))
          } else if (value !== this.staff.password) {
            callback(new Error("两次输入密码不一致!"))
          } else {
            callback()
          }
        } else {
          if (this.staff.password) {
            if (!value) {
              callback(new Error("请再次输入密码"))
            } else if (value !== this.staff.password) {
              callback(new Error("两次输入密码不一致!"))
            } else {
              callback()
            }
          } else {
            if (value != this.staff.password) {
              callback(new Error("两次输入密码不一致!"))
            } else {
              callback()
            }
          }
        }
      } else {
        callback()
      }
    }
    // 验证角色
    const validateRole = (rule, value, callback) => {
      if (this.staff.userName) {
        if (value.length == 0) {
          callback(new Error("登录账号不为空时，角色不能为空"))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    return {
      // dialogVisibleShow: false,
      saveDisabled: false,
      dialogType: "new",
      activeName: "basicInfo",
      photoImageUrl: "",
      esignImageUrl: "",
      rules: {
        staffCode: [
          { required: true, message: "员工工号不能为空", trigger: "blur" },
          { trigger: "blur", validator: validateStaffCode }
        ],
        name: [
          { required: true, message: "员工姓名不能为空", trigger: "blur" },
          { trigger: "blur", validator: validateStaffName }
        ],
        idCard: [
          { required: true, message: "身份证号不能为空", trigger: "blur" },
          { trigger: "blur", validator: validateIdCard }
        ],
        hisDeptId: [
          { required: true, message: "科室不能为空", trigger: "blur" },
          { trigger: "blur", validator: validateStaffDept }
        ],
        titleCode: [
          { required: true, message: "职称不能为空", trigger: "blur" }
        ],
        businessType: [
          { required: true, message: "业务类别不能为空", trigger: "blur" }
        ],
        telephone: [
          {
            required: true,
            pattern: /^1[34578]\d{9}$/,
            message: "手机号码须为11位数字，以1开头，第二位为3、4、5、7、8",
            trigger: "blur"
          },
          { trigger: "blur", validator: validaTelephone }
        ],
        qualifId: [
          { required: true, message: "资质编码不能为空", trigger: "blur" }
        ],
        userName: [
          { validator: validateSysUserName, trigger: "blur" },
          { validator: validateUserNameExist, trigger: "blur" }
        ],
        password: [{ validator: validatePassword, trigger: "blur" }],
        confirmPassword: [
          { validator: validateConfirmPassword, trigger: "blur" }
        ],
        roleIdArr: [{ validator: validateRole, trigger: "blur" }]
      },
      staff: Object.assign({}, defaultStaff),
      staffFormParam: "", // 医护人员表单要提交的参数
      deptTreeData: [],
      orgTreeData: [],
      // 民族
      nationOptions: [
        {
          basicId: "95A54567D950C1FCE050000000007521",
          entryCode: "01 ",
          entryValue: "汉族",
          disable: false
        },
        {
          basicId: "95A54567D951C1FCE050000000007521",
          entryCode: "02 ",
          entryValue: "蒙古族",
          disable: false
        },
        {
          basicId: "95A54567D952C1FCE050000000007521",
          entryCode: "03 ",
          entryValue: "回族",
          disable: false
        },
        {
          basicId: "95A54567D953C1FCE050000000007521",
          entryCode: "04 ",
          entryValue: "藏族",
          disable: false
        },
        {
          basicId: "95A54567D954C1FCE050000000007521",
          entryCode: "05 ",
          entryValue: "维吾尔族",
          disable: false
        },
        {
          basicId: "95A54567D955C1FCE050000000007521",
          entryCode: "06 ",
          entryValue: "苗族",
          disable: false
        },
        {
          basicId: "95A54567D956C1FCE050000000007521",
          entryCode: "07 ",
          entryValue: "彝族",
          disable: false
        },
        {
          basicId: "95A54567D957C1FCE050000000007521",
          entryCode: "08 ",
          entryValue: "壮族",
          disable: false
        }
      ],
      // 婚姻状态
      maritalOptions: [
        {
          basicId: "14aa1b38c1bef0923e61ef1a62d6edbb",
          entryCode: "10",
          entryValue: "未婚",
          disable: false
        },
        {
          basicId: "14fc06868231bc1f69f56f2903746234",
          entryCode: "20",
          entryValue: "已婚",
          disable: false
        },
        {
          basicId: "8d51d6bc30691ccfce4a47686135bcb3",
          entryCode: "21",
          entryValue: "初婚",
          disable: false
        },
        {
          basicId: "82dbad15f664338ed058d95deda8c9b7",
          entryCode: "22",
          entryValue: "再婚",
          disable: false
        },
        {
          basicId: "53489db8bd4226963c2b74a5a4156efc",
          entryCode: "23",
          entryValue: "复婚",
          disable: false
        },
        {
          basicId: "8ed4dd014727cf0b0d4ae03d0fdb3eb6",
          entryCode: "30",
          entryValue: "丧偶",
          disable: false
        },
        {
          basicId: "240ea33a6f71c4cdf9e3036e55036e25",
          entryCode: "40",
          entryValue: "离婚",
          disable: false
        },
        {
          basicId: "941fe8369ad7241bc1ba089508a25d74",
          entryCode: "90",
          entryValue: "未说明的婚姻状况",
          disable: false
        }
      ],
      // 学历
      educationOptions: [
        {
          basicId: "7a3c37788f59c6990b1cf0dddb18830b",
          entryCode: "43",
          entryValue: "中等专科肄业",
          disable: false
        },
        {
          basicId: "455a9337b8fa927a70d66132bb641b95",
          entryCode: "44",
          entryValue: "职业高中毕业",
          disable: false
        },
        {
          basicId: "2dccf2d05de9e01d7123437ed1e12c25",
          entryCode: "45",
          entryValue: "职业高中结业",
          disable: false
        },
        {
          basicId: "10abc3f97623424b7f81c67246431905",
          entryCode: "46",
          entryValue: "职业高中肄业",
          disable: false
        },
        {
          basicId: "fc42f63ec6ddde45f4fe9863520beb08",
          entryCode: "48",
          entryValue: "技工学校毕业",
          disable: false
        },
        {
          basicId: "370adb0b1f286692ecc18648eee80f22",
          entryCode: "48",
          entryValue: "技工学校结业",
          disable: false
        },
        {
          basicId: "97e15aac61a2b97eb9113b02ac48d838",
          entryCode: "49",
          entryValue: "技工学校肄业",
          disable: false
        },
        {
          basicId: "a601973cfcdc78b6a4666038ce27630f",
          entryCode: "60",
          entryValue: "普通高级中学教育",
          disable: false
        },
        {
          basicId: "66f435fff37930343a217ae01fe0f4a5",
          entryCode: "61",
          entryValue: "普通高中毕业",
          disable: false
        },
        {
          basicId: "2f07aa5358523ffd273a142fda55a97f",
          entryCode: "63",
          entryValue: "普通高中肄业",
          disable: false
        },
        {
          basicId: "c85a33da2e72487412ecb53aa9596b59",
          entryCode: "70",
          entryValue: "初级中学教育",
          disable: false
        },
        {
          basicId: "9ff641bfa9f772e640fa1cd33ad00b50",
          entryCode: "71",
          entryValue: "初中毕业",
          disable: false
        },
        {
          basicId: "4c2600b376c6c4bf06682e56d91f9605",
          entryCode: "73",
          entryValue: "初中肄业",
          disable: false
        },
        {
          basicId: "f641e4fd3db203dcf9ebd2a8f0b04228",
          entryCode: "80",
          entryValue: "小学教育",
          disable: false
        },
        {
          basicId: "535e99d216bfa85a0cabd19e796162f3",
          entryCode: "81",
          entryValue: "小学毕业",
          disable: false
        },
        {
          basicId: "2d013fa8fe1fd8a31fe378cfeade5983",
          entryCode: "83",
          entryValue: "小学肄业",
          disable: false
        },
        {
          basicId: "e5b456dea666c303dbc432bd3a856049",
          entryCode: "90",
          entryValue: "其他",
          disable: false
        },
        {
          basicId: "74e13a71f6b15eb99865a0ad188dea31",
          entryCode: "15",
          entryValue: "硕士研究生结业",
          disable: false
        },
        {
          basicId: "407850d58286a292f3cb64e594c20981",
          entryCode: "16",
          entryValue: "硕士研究生肄业",
          disable: false
        },
        {
          basicId: "48f0019e6d0fe84538006f0b64e1f1ab",
          entryCode: "17",
          entryValue: "研究生班毕业",
          disable: false
        },
        {
          basicId: "b3db7a6f9859e0df86c7f1f8d11fe0c8",
          entryCode: "18",
          entryValue: "研究生班结业",
          disable: false
        },
        {
          basicId: "9c70766ef50edff8ebc92c6b3ad66030",
          entryCode: "20",
          entryValue: "大学本科",
          disable: false
        },
        {
          basicId: "fc43b9fb53ce5c3048685109f58790a1",
          entryCode: "32",
          entryValue: "大学专科结业",
          disable: false
        },
        {
          basicId: "7cdf695e0a14f32f47ab13c31cb620b4",
          entryCode: "33",
          entryValue: "大学专科肄业",
          disable: false
        },
        {
          basicId: "f2fd87b03943fdd88c9b9d75542943b7",
          entryCode: "40",
          entryValue: "中等职业教育",
          disable: false
        },
        {
          basicId: "7d9b88ad78ab6ebb5b2e8c46ed9a6433",
          entryCode: "41",
          entryValue: "中等专科毕业",
          disable: false
        },
        {
          basicId: "9696a24dece7d039d7b9c4766fcd03ee",
          entryCode: "42",
          entryValue: "中等专科结业",
          disable: false
        },
        {
          basicId: "3bedaf711284ce2b91c92d8881e5676c",
          entryCode: "19",
          entryValue: "研究生班肄业",
          disable: false
        },
        {
          basicId: "8948f8d8134a66d6640c723f4518754f",
          entryCode: "62",
          entryValue: "普通高中结业",
          disable: false
        },
        {
          basicId: "c30682dee4db003fa6632db9851f043e",
          entryCode: "10",
          entryValue: "研究生教育",
          disable: false
        },
        {
          basicId: "020d1a98d49b621864c7af0100ce322e",
          entryCode: "11",
          entryValue: "博士研究生毕业",
          disable: false
        },
        {
          basicId: "55a370220fd2c7f132439a43ef040996",
          entryCode: "12",
          entryValue: "博士研究生结业",
          disable: false
        },
        {
          basicId: "2e8cdbbb71861cba8a2f1caf3342eaad",
          entryCode: "13",
          entryValue: "博士研究生肄业",
          disable: false
        },
        {
          basicId: "4926ed79365413ceff7a70272aa25ac7",
          entryCode: "14",
          entryValue: "硕士研究生毕业",
          disable: false
        },
        {
          basicId: "86283455c46dbec5a6ca10f1349d2582",
          entryCode: "30",
          entryValue: "专科教育",
          disable: false
        },
        {
          basicId: "6bf86ea2e6734a34b6d13b630dad35c5",
          entryCode: "28",
          entryValue: "大学普通班毕业",
          disable: false
        },
        {
          basicId: "f397049c6c8a4688c814a14342157e75",
          entryCode: "31",
          entryValue: "大学专科毕业",
          disable: false
        },
        {
          basicId: "d6d10d5a2f5fda1fcb8807e799bf4fd1",
          entryCode: "21",
          entryValue: "大学本科毕业",
          disable: false
        },
        {
          basicId: "896b7e227775300f3bf92b6c8078e98d",
          entryCode: "22",
          entryValue: "大学本科结业",
          disable: false
        },
        {
          basicId: "a88a929c2c0ba9171d358cd3c0a4890a",
          entryCode: "23",
          entryValue: "大学本科肄业",
          disable: false
        }
      ],
      // 证件类型
      certificateOptions: [
        {
          basicId: "5aa7f80d333d1650665cf2f72d9a5114",
          entryCode: "08",
          entryValue: "士兵证",
          disable: false
        },
        {
          basicId: "f790ef88188129d1accf5a70f34d32f7",
          entryCode: "99",
          entryValue: "其他法定有效证件",
          disable: false
        },
        {
          basicId: "b198a0f734f1fbf6814dfc1c66307b0b",
          disable: false,
          entryCode: "07",
          entryValue: "台湾居民来往内地通行证"
        },
        {
          basicId: "e39b963c14c2f5096cf7e56bac4e0b04",
          entryCode: "01",
          entryValue: "居民身份证",
          disable: false
        },
        {
          basicId: "73524b2053b3ebdefbbc685e565a1995",
          entryCode: "02",
          entryValue: "居民户口簿",
          disable: false
        },
        {
          basicId: "dfea974f9d6fbf46846a8cb795c86d1a",
          entryCode: "03",
          entryValue: "护照",
          disable: false
        },
        {
          basicId: "721553ed97fd9cbed0ab260133b2e52f",
          entryCode: "04",
          entryValue: "军官证",
          disable: false
        },
        {
          basicId: "0439510c8bea1aa4c0976ce7643163ce",
          entryCode: "05",
          entryValue: "驾驶证",
          disable: false
        },
        {
          basicId: "173a9f09bef8d1b60d87124a80a03c53",
          disable: false,
          entryCode: "06",
          entryValue: "港澳居民来往内地通行证"
        }
      ],
      // 资质编码   医生职称
      titleCodeOptions: [
        {
          createBy: "Admin30",
          createTime: null,
          delFlag: 0,
          hisCode: "2",
          hisDicId: "961EB85397629030E0500000000064B9",
          hisDicTypeId: "63ab577026c7198faf0567de75b219bb",
          lastUpdateBy: "A9FB2CFFF152F2FBE0530100007FF973",
          lastUpdateTime: "2020-07-15 16:29:45",
          provincialCode: "	244",
          provincialFivestrokesCode: "1",
          provincialName: "	药师",
          provincialSyllablesCode: "YS",
          remarks: "	药师",
          standardCode: "	244",
          standardFivestrokesCode: "	AJ",
          standardName: "	药师",
          standardSyllablesCode: "YS",
          status: 1,
          systemFlag: 0
        },
        {
          createBy: "Admin30",
          createTime: null,
          delFlag: 0,
          hisCode: "2",
          hisDicId: "961EB853975F9030E0500000000064B9",
          hisDicTypeId: "63ab577026c7198faf0567de75b219bb",
          lastUpdateBy: "A9FB2CFFF152F2FBE0530100007FF973",
          lastUpdateTime: "2020-07-15 16:29:32",
          provincialCode: "	241",
          provincialFivestrokesCode: "1",
          provincialName: "	主任药师",
          provincialSyllablesCode: "ZRYS",
          remarks: "	主任药师",
          standardCode: "	241",
          standardFivestrokesCode: "	YWAJ",
          standardName: "	主任药师",
          standardSyllablesCode: "ZRYS",
          status: 1,
          systemFlag: 0
        },
        {
          createBy: "A7C9C431043CE2B9E05011AC02007487",
          createTime: "2020-06-19 17:25:10",
          delFlag: 0,
          hisCode: "3",
          hisDicId: "ae96f290330512b4f40bc9fcd23ca85f",
          hisDicTypeId: "63ab577026c7198faf0567de75b219bb",
          lastUpdateBy: "A9FB2CFFF152F2FBE0530100007FF973",
          lastUpdateTime: "2020-07-15 16:25:33",
          provincialCode: "265",
          provincialFivestrokesCode: "RF",
          provincialName: "技士",
          provincialSyllablesCode: "JS",
          remarks: null,
          standardCode: "265",
          standardFivestrokesCode: "RF",
          standardName: "技士",
          standardSyllablesCode: "JS",
          status: 1,
          systemFlag: 0
        },
        {
          createBy: "A7C9C431043CE2B9E05011AC02007487",
          createTime: "2020-06-19 17:26:30",
          delFlag: 0,
          hisCode: "1",
          hisDicId: "ee192178e1508c896ff8b04577b24e2d",
          hisDicTypeId: "63ab577026c7198faf0567de75b219bb",
          lastUpdateBy: "A9FB2CFFF152F2FBE0530100007FF973",
          lastUpdateTime: "2020-07-09 20:06:01",
          provincialCode: "134",
          provincialFivestrokesCode: "EGWYJ",
          provincialName: "助理会计师",
          provincialSyllablesCode: "ZLHJS",
          remarks: null,
          standardCode: "134",
          standardFivestrokesCode: "EGWYJ",
          standardName: "助理会计师",
          standardSyllablesCode: "ZLHJS",
          status: 1,
          systemFlag: 0
        },
        {
          createBy: "Admin30",
          createTime: null,
          delFlag: 0,
          hisCode: "1",
          hisDicId: "961EB85397599030E0500000000064B9",
          hisDicTypeId: "63ab577026c7198faf0567de75b219bb",
          lastUpdateBy: "A9FB2CFFF152F2FBE0530100007FF973",
          lastUpdateTime: "2020-07-15 16:22:58",
          provincialCode: "	231",
          provincialFivestrokesCode: "1",
          provincialName: "主任医师",
          provincialSyllablesCode: "ZRYS",
          remarks: "	主任医师",
          standardCode: "	231",
          standardFivestrokesCode: "	YWAJ",
          standardName: "主任医师",
          standardSyllablesCode: "ZRYS",
          status: 1,
          systemFlag: 0
        },
        {
          createBy: "Admin30",
          createTime: null,
          delFlag: 0,
          hisCode: "1",
          hisDicId: "961EB853975C9030E0500000000064B9",
          hisDicTypeId: "63ab577026c7198faf0567de75b219bb",
          lastUpdateBy: "A9FB2CFFF152F2FBE0530100007FF973",
          lastUpdateTime: "2020-07-15 16:22:48",
          provincialCode: "234",
          provincialFivestrokesCode: "1",
          provincialName: "医师",
          provincialSyllablesCode: "YS",
          remarks: "	医师",
          standardCode: "234",
          standardFivestrokesCode: "	AJ",
          standardName: "医师",
          standardSyllablesCode: "YS",
          status: 1,
          systemFlag: 0
        }
      ],
      // 设置权限角色
      roles: [],
      oldUserName: "",
      headers: {
        // Authorization: "Bearer " + store.getters.access_token
      },
      photoUploadAddr: "/basic/file/upload",
      esignatureUploadAddr: "/basic/file/upload",
      choosedNodeType: "", // 科室树被选中节点类型（机构或科室）
      choosedNodeIsLeaf: false, // 科室树被选中节点是否叶子节点
      choosedNodeDeptCategory: undefined, // 科室树被选中节点的科室类别
      oldStaffDept: "",
      staff_btn_add: false,
      staff_btn_update: false,
      // 模拟数据
      userInfo: JSON.parse(sessionStorage.getItem("user")).sysUser
    }
  },
  created() {
    // 获取其他证件类型
    // this.getCertificateType()
    // 民族下拉框获取民族
    // this.getNation()
    // 获取婚姻状况
    // this.getMaritalStatus()
    // 获取学历
    // this.getEducation()
    // 获取资质编码（职称）
    // this.getProfessionalRank()
  },
  mounted() {
    this.initRoles() // 获取角色
  },
  methods: {
    init() {
      console.log("123")
      console.log(this.selectedDept)
      console.log(this.organizationId)
      this.staff = Object.assign({}, defaultStaff)
      this.activeName = "basicInfo"
      // this.dialogVisible = true;
      this.dialogType = "new"
      // 重写一个表单上传方法
      this.staffFormParam = new FormData()
      // 清空照片和电子签名url
      this.photoImageUrl = ""
      this.esignImageUrl = ""
      // 清除表单检验结果
      this.$nextTick(() => {
        this.$refs["staffForm"].clearValidate()
        this.$refs["systemAccountForm"].clearValidate()
      })
      this.getSysOrg()
      if (this.selectedDept) {
        this.deptTreeData = [
          {
            id: this.selectedDept.id,
            label: this.selectedDept.label,
            children: null
          }
        ]
        this.choosedNodeType = this.selectedDept.type
        this.choosedNodeIsLeaf = this.selectedDept.leaf
        this.choosedNodeDeptCategory = this.selectedDept.deptCategory
        this.staff.sysOrganizationId = this.selectedDept.sysOrganizationId
        this.staff.hisDeptId = this.selectedDept.id
      }
    },
    getSysOrg() {
      let organId =
        this.dialogType === "edit"
          ? this.staff.sysOrganizationId
          : this.userInfo.sysOrganizationId
      console.log(organId)
      getCurrentSysOrg(organId).then(response => {
        console.log(response)
        let orgInfo = response.data
        console.log(orgInfo)
        this.deptTreeData = orgInfo.map(e => ({
          id: e.sysOrganizationId,
          label: e.name,
          children: null,
          type: "org",
          maxChildId: e.maxChildId
        }))
      })
    },
    // 点击修改按钮回显
    handleUpdateStaff(medStaff) {
      console.log(medStaff)
      this.staff = Object.assign({}, medStaff)
      this.staff.confirmPassword = this.staff.password = ""

      this.activeName = "basicInfo"
      this.dialogType = "edit"
      // this.dialogVisible = true;
      this.oldUserName = medStaff.userName
      // 新增时记录员工工号初始值，若工号不变则该输入框失去焦点时不校验工号是否重复
      this.oldStaffCodeVal = medStaff.staffCode
      // 修改时记录员工的科室，若科室不变则不校验科室
      this.oldStaffDept = medStaff.hisDeptId
      // 重写一个表单上传方法
      this.staffFormParam = new FormData()
      // 照片与电子签名回显
      this.photoImageUrl = medStaff.photoUrl
      this.esignImageUrl = medStaff.eSignature

      // 清除表单检验结果
      this.$nextTick(() => {
        this.$refs["staffForm"].clearValidate()
        this.$refs["systemAccountForm"].clearValidate()
      })

      this.getSysOrg()
      this.deptTreeData = [
        {
          id: medStaff.hisDeptId,
          label: medStaff.deptName,
          children: null
        }
      ]
    },
    // 延迟下拉框树
    loadDeptOptions({ action, parentNode, callback }) {
      // console.log(action)
      // console.log("123")
      // 加载根节点
      let organId =
        this.dialogType === "edit"
          ? this.staff.sysOrganizationId
          : this.userInfo.sysOrganizationId
      if (action === LOAD_ROOT_OPTIONS) {
        getCurrentSysOrg("").then(response => {
          console.log(response)
          let orgInfo = response.data

          this.deptTreeData = orgInfo.map(e => ({
            id: e.sysOrganizationId,
            label: e.name,
            children: null,
            type: "org",
            maxChildId: e.maxChildId
          }))
        })
      } else if (action === LOAD_CHILDREN_OPTIONS) {
        // 当前节点为机构
        console.log(parentNode)
        if (parentNode.type == "org") {
          // 若当前机构下不包含机构了，查询该机构下的科室
          if (null == parentNode.maxChildId) {
            let parentId = "-1"
            let queryParam = {
              sysOrganizationId: parentNode.id,
              hisDeptId: parentId,
              departmentTypeList: departmentType.administrationDept
            }
            console.log(queryParam)
            getDeptsBySysOrgId(queryParam).then(response => {
              let rootDeptInfo = response.data
              let rootDeptNode = rootDeptInfo.map(e => ({
                id: e.id,
                label: e.label,
                children: null,
                isLeaf: e.leaf,
                type: e.type,
                sysOrganizationId: e.sysOrganizationId,
                deptCategory: e.deptCategory
              }))
              parentNode.children = rootDeptNode.concat()
              callback()
            })
          }
          // 当前机构还有下级机构，则查询它的下级机构
          else {
            getOrgAndDeptLazyLoad(parentNode.id).then(response => {
              let orgOrDeptInfo = response.data
              let orgNode = orgOrDeptInfo.map(e => ({
                id: e.id,
                label: e.label,
                children: null,
                isLeaf: e.leaf,
                type: e.type,
                maxChildId: e.maxChildId
              }))
              parentNode.children = orgNode.concat()
              callback()
            })
          }
        }
        // 当前节点为科室（查询下级科室）
        else {
          let params = {
            hisDeptId: parentNode.id,
            departmentTypeList: departmentType.administrationDept,
            deptCategoryList: deptCategory.administrationDept
          }
          getChildDeptByHisDeptId(params).then(response => {
            let deptNodeInfo = response.data
            let deptNode = deptNodeInfo.map(e => ({
              id: e.id,
              label: e.label,
              children: null,
              isLeaf: e.leaf,
              type: e.type,
              maxChildId: e.maxChildId,
              sysOrganizationId: e.sysOrganizationId,
              deptCategory: e.deptCategory
            }))
            parentNode.children = deptNode.concat()
            callback()
          })
        }
      }
    },
    // 自定义键名
    normalizer(node) {
      // 去掉children=[]的children属性
      if (node.children && !node.children.length) {
        delete node.children
      }
    },
    // 选中科室，给科室所在的机构赋值
    chooseDept(node) {
      this.staff.sysOrganizationId = node.sysOrganizationId
      this.staff.hisDeptId = node.id
      this.choosedNodeType = node.type
      this.choosedNodeIsLeaf = node.isLeaf
      this.choosedNodeDeptCategory = node.deptCategory
      this.$refs["staffForm"].validateField("hisDeptId")
    },

    //  获取其他证件类型
    getCertificateType() {
      getDrugType(zjlxCode).then(response => {
        if (response.data && response.data.code === "1000") {
          this.certificateOptions = response.data.data
        }
      })
    },

    // 获取民族下拉框数据
    getNation() {
      getDrugType(mzdmCode).then(response => {
        if (response.data && response.data.code === "1000") {
          this.nationOptions = response.data.data
          // 民族按名称首字母排序
          this.nationOptions.sort((a, b) =>
            a.entryValue.localeCompare(b.entryValue)
          )
        }
      })
    },
    // 获取婚姻状况
    getMaritalStatus() {
      getDrugType(hyzkdmCode).then(response => {
        if (response.data && response.data.code === "1000") {
          this.maritalOptions = response.data.data
        }
      })
    },
    // 获取学历
    getEducation() {
      getDrugType(xldmCode).then(response => {
        if (response.data && response.data.code === "1000") {
          this.educationOptions = response.data.data
        }
      })
    },
    // 获取资质编码（职称）
    getProfessionalRank() {
      let val = "basic"
      getDoctorTitle({
        typeDicCode: zyjszwdmCode,
        val: val
      }).then(response => {
        if (response.data && response.data.code === "1000") {
          this.titleCodeOptions = response.data.data
        }
      })
    },

    // 获取角色
    initRoles() {
      getAllRoleIdAndName()
        .then(r => {
          // console.log(r)
          this.roles = r.data
        })
        .catch(error => {
          this.$message({
            message: "获取数据失败",
            type: "error"
          })
        })
    },

    // 确认提交
    confirmStaff() {
      this.$refs.staffForm.validate(valid => {
        if (!valid) {
          return false
        } else {
          // 系统账号tab中登录账号不为空，校验系统账号信息
          if (this.staff.userName) {
            this.$refs.systemAccountForm.validate(accountValid => {
              if (!accountValid) {
                return false
              } else {
                this.saveMedicalStaff()
                this.handleClose()
              }
            })
          } else {
            if (this.staff.sysUserId) {
              this.$refs.systemAccountForm.validate(accountValid => {
                if (!accountValid) {
                  return false
                } else {
                  this.saveMedicalStaff()
                  this.handleClose()
                }
              })
            } else {
              this.$refs["systemAccountForm"].clearValidate()
              this.saveMedicalStaff()
              this.handleClose()
            }
          }
        }
      })
    },

    saveMedicalStaff() {
      const isEdit = this.dialogType === "edit"
      // 上传照片和电子签名后，给员工的照片地址和签名地址赋值
      this.staff.photoUrl = this.photoImageUrl
      this.staff.eSignature = this.esignImageUrl
      if (this.staff.roleIdArr.length > 0) {
        this.staff.roleId = this.staff.roleIdArr.join(",")
      }
      // 修改医护人员
      if (isEdit) {
        this.saveDisabled = true
        updateMedicalStaff(qs.stringify(this.staff)).then(res => {
          this.saveDisabled = false
          if (res.code === "1000") {
            this.dialogVisible = false
            this.$emit("refreshMedicialStaff")
            this.$message({
              message: "修改成功",
              type: "success",
              duration: 2000
            })
          } else {
            this.$message({
              message: res.msg,
              type: "error",
              duration: 2000
            })
          }
        })
      }
      // 新增医护人员
      else {
        // 设置机构id
        this.saveDisabled = true
        addMedicalStaff(qs.stringify(this.staff)).then(res => {
          this.saveDisabled = false
          if (res.data && res.data.code === "1000") {
            this.dialogVisible = false
            this.$emit("refreshMedicialStaff")
            this.$message({
              message: "新增成功",
              type: "success",
              duration: 2000
            })
          } else {
            this.$message({
              message: res.data.msg,
              type: "error",
              duration: 2000
            })
          }
        })
      }
    },

    resetTabInfo() {
      if (this.activeName == "basicInfo") {
        this.$refs["staffForm"].clearValidate()
        this.staff.staffCode = ""
        this.staff.name = ""
        this.staff.idCard = ""
        this.staff.sex = ""
        this.staff.birthday = ""
        this.staff.otherCredType = ""
        this.staff.otherCredEntial = ""
        this.staff.nation = ""
        this.staff.maritalStatus = ""
        this.staff.education = ""
        this.staff.qualifId = ""
        this.staff.hisDeptId = null
        this.staff.titleCode = ""
        this.staff.businessType = ""
        this.staff.telephone = ""
        this.staff.address = ""
      } else if (this.activeName == "resume") {
        this.staff.profiles = ""
        this.staff.expertise = ""
        this.staff.honour = ""
      } else if (this.activeName == "systemAccount") {
        this.$refs["systemAccountForm"].clearValidate()
        this.staff.password = this.staff.confirmPassword = defaultPassword
        this.staff.userName = ""
        this.staff.roleIdArr = []
      }
    },

    // 关闭弹框
    handleClose() {
      this.resetTabInfo()
      this.$emit("update:dialogVisibleShow", false)
    },
    // 取消按钮
    cancel() {
      this.handleClose()
    },
    // 确认提交
    submit() {
      console.log("点击提交按钮了")
      this.handleClose()
    }
  }
}
</script>
<style lang="scss" scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
